import json
import socket
import struct
from interface import common_interface, admin_interface
from lib import common
from concurrent.futures import ThreadPoolExecutor
from threading import Lock
from TcpServer import user_data


pool = ThreadPoolExecutor(10)
mutex = Lock()
user_data.mutex = mutex


func_dic = {
	'register': common_interface.register,
	'login': common_interface.login,
	'check_movie': admin_interface.check_movie,
	'upload_movie': admin_interface.upload_movie,
}


def get_server():
	server = socket.socket()
	server.bind(('127.0.0.1', 8080))
	server.listen(5)
	while 1:
		conn, address = server.accept()
		# 直接开启多线程交给下面不同的人去干
		pool.submit(working, conn, address)


def dispatch(conn, back_dic):
	if back_dic['type'] in func_dic:
		func_dic.get(back_dic['type'])(conn, back_dic)
	else:
		send_dic = {'flag': False, 'msg': "请求不合法..."}
		common.send_msg(conn, send_dic)


def working(conn, address):
	while 1:
		# 对当前的的客户端连接进行异常检测...
		try:
			header = conn.recv(4)
			# print(header)
			data_bytes = conn.recv(struct.unpack('i', header)[0])
			back_dic = json.loads(data_bytes.decode("utf-8"))
			back_dic['address'] = str(address)
			dispatch(conn, back_dic)
		except Exception as e:
			conn.close()
			user_data.mutex.acquire()
			user_data.alive_user.pop(str(address))
			user_data.mutex.release()
			print(e)
			# 客户端产生异常就直接退出了
			break

